$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
    console.log('Data ready event triggered');
    var mstform = $NG.getCmpApi("p_form_impl_cost_budget");
    var dgrid1 = $NG.getCmpApi('p_form_impl_labor_budget');//实施人工
    var dgrid2 = $NG.getCmpApi('p_form_impl_daliy_budget');//日常费用
    var dgrid3 = $NG.getCmpApi('p_form_impl_sec_dev_budget');//二次开发费用



    // useUpdateRow(({args})=>{
    //     console.log(`监听到了`);
    //     const _arr = args[0]
    //     console.log(_arr.u_budget_account);
    //     const _isBy = [8570000000000621,8570000000000622]
    //     if(_arr.u_budget_account==8570000000000621||){
    //         $NG.alert("未包含项目激励。")
    //     }
    // },"p_form_impl_daliy_budget")8570000000000340   8570000000000341
    useDataIndexChange(({args})=>{
        console.log(args[0]);
    },"u_expense_code")
    useClick(()=>{
        let lock = false
        const _isBy = ['8570000000000340','8570000000000341','8570000000000368',"8570000000000369"]
        console.log(`监听到了`);
        const _arr = dgrid2.getRows()
        _arr.forEach(item=>{
        console.log('监听值',item.u_expense_code);
        if(_isBy.indexOf(String(item.u_expense_code))!==-1){
                lock = true
            }
            console.log(item.u_expense_code);
        })

        if(!lock){
            $NG.alert("未包含项目激励。")
        }
    },"save")

    {//初始化逻辑BEGIN
        if (mstform) {
            console.log(mstform.name + ' is ready');
            cntMFilter();
            getPtInfoByPhid();
        } else {
            console.error('mstform is not available');
        };
    }//初始化逻辑END

	if (page.oType == "add" || page.oType == "edit") {
		$NG.updateState((updater) => {
			updater.data.p_form_impl_cost_budget.setProps({
				u_fitime:
					"FY" + formatDate(new Date(), "yyyy-mm").replace("-", ".M"),
			});
		});
		//表头多字段设置属性
		$NG.updateUI((updater) => {
			updater.fieldSetForm.p_form_impl_cost_budget.u_fitime.setProps({
				hidden: true, //隐藏
			});
		});
	}

if(page.oType == 'add'){
    $NG.execServer("getCostPc",{u_sequence:"02"},(res)=>{
        if(res.count == 0) return
        const _data = JSON.parse(res.data)
        console.log(`费用项目`,_data);
        dgrid2.addRows(_data.reduce((value,item)=>{
            const el = item.extendObjects
            value.push({
                u_expense_code:el.u_ficost_pc,
                u_expense_code_EXName:el.u_name,
                u_expense_description:el.u_describe
            })
            return value
        },[]))
    })
}

    {//表头字段变化逻辑BEGIN
            getCntCount("p_form_impl_cost_budget","u_cnt",getCntMInfoByPhid)
            
        useValuesChange(({ args }) => {
            cntMFilter();
            getPtInfoByPhid();
            getCntCount("p_form_impl_cost_budget","u_cnt",getCntMInfoByPhid)
        }, 'p_form_impl_cost_budget.phid_pc');
        useValuesChange(({ args }) => {
            getCntMInfoByPhid();
        }, 'p_form_impl_cost_budget.u_cnt');

    }//表头字段变化逻辑END

    function sun(){
        $NG.updateState((updater)=>{
            updater.data.p_form_impl_cost_budget.setProps({
                u_ss_rate:(Number(mstform.getItem("u_total_impl_amt").getValue())/Number(mstform.getItem("u_cnt_amt_vat").getValue())).toFixed(2)
            })
        })
    }

    {//表体字段汇总逻辑BEGIN
        useUpdateRows(({ args }) => {
            caculatedgrid()
            sun()   
        }, "p_form_impl_labor_budget");

        useUpdateRows(({ args }) => {
            caculatedgrid()
            //默认年度
		args[0].forEach((item) => {
			if (!item.u_year) {
				item.u_year = new Date().getFullYear()
				item.u_year_EXName = new Date().getFullYear()
			}
		});
            dgrid2.refreshView()
        }, "p_form_impl_daliy_budget");

        useUpdateRows(({ args }) => {
            caculatedgrid()
        }, "p_form_impl_sec_dev_budget");
    }//表体字段汇总逻辑END



    function getPtInfoByPhid() {
        if (mstform.getItem('phid_pc').getValue()) {
            $NG.execServer('getPtInfoByPhid', { phid: mstform.getItem('phid_pc').getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_impl_cost_budget.setProps({
                        u_pc_no: datas.pc_no//项目编号
                        , u_agreed_sts_dt: datas.start_date//计划完工日期
                        , u_agreed_pcl_dt: datas.end_date//计划竣工日期
                        , u_sqgw: {//售前顾问
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        u_region: {//事业部or组织
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        u_regional_center: {//区域中心
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        u_product_line: {//产品线
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        u_dept: {//部门
                            value: datas.dept_phid,
                            label: datas.dept_name,
                        },
                        u_pc_type: {//项目类型
                            value: datas.type_phid,
                            label: datas.type_name,
                        },
                        u_pc_overview :datas.descript
                    });
                });

            });
        }
    }

    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_impl_cost_budget.u_cnt.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = mstform.getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!mstform.getItem('phid_pc').getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,
                        phid_pc: mstform.getItem('phid_pc').getValue()
                    }
                }),
            });
        });
    }

    function getCntMInfoByPhid(params) {
        $NG.execServer('getCntMInfoByPhid', { phid: mstform.getItem('u_cnt').getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            //帮助字段赋值
            $NG.updateState((updater) => {
                //【注意这里的表名不能为控件ID，必须要是表名】
                updater.data.p_form_impl_cost_budget.setProps({
                    u_cnt_no: datas.pcm_no,//合同编码
                    u_cnt_amt_vat: datas.cnt_sum_vat_fc,//合同价税合计
                    u_invoice_type: {//发票类型
                        value: datas.invoice_type_phid,
                        label: datas.invoice_type_name,
                    }
                });
            });

        });
    }

    function caculatedgrid() {
        console.log(`监听生效`);
		let u_total_impl_labor_amt = 0; //实施人工费
		let u_total_daily_amt = 0; //合计日常费用
		let u_total_sec_dev_amt = 0; //合计二次开发费用
		let u_total_impl_amt = 0; //合计总费用
		const Rows1 = dgrid1.getRows(); //设备清单页签
		const Rows2 = dgrid2.getRows(); //实施费页签
		const Rows3 = dgrid3.getRows(); //服务费页签
        //实施费用合计
        //人工

		dgrid1.getRows().forEach((items) => {
            let total = 0
            for(let i = 1;i<=12;i++){
                const str = "u_man_days_"+String(i).padStart(2,"0");
                total += (Number(items[str]) || 0)
            }
            items.u_labor_amt = total
			u_total_impl_labor_amt += parseFloat(items.u_labor_amt) || 0; //合同现额
		});
		Rows2.forEach((items) => {
            let total = 0
            for(let i = 1;i<=12;i++){
                const str = "u_expenses_"+String(i).padStart(2,"0");
                total += (Number(items[str]) || 0)
            }
            items.u_annual_impl_amt = total
			u_total_daily_amt += parseFloat(items.u_annual_impl_amt);
		});
		Rows3.forEach((items) => {
			u_total_sec_dev_amt += parseFloat(items.u_sec_dev_amt);
		});

		u_total_impl_amt =
			u_total_impl_labor_amt + u_total_daily_amt + u_total_sec_dev_amt;

		$NG.updateState((updater) => {
			updater.data.p_form_impl_cost_budget.setProps({
				u_total_impl_labor_amt: u_total_impl_labor_amt, //
				u_total_daily_amt: u_total_daily_amt, //
				u_total_sec_dev_amt: u_total_sec_dev_amt, //
				u_total_impl_amt: u_total_impl_amt, //
			});
		});
        dgrid1.refreshView()
		
	}
    payProjectFilter()
    function payProjectFilter() {
		$NG.updateUI((updater) =>
			updater.editGrid.p_form_impl_daliy_budget.u_expense_code.setProps((p) => {
                console.log(`参数检查`,updater);
				return {
					...p,
					editor: {
						...p.editor,
						clientSqlFilter: {
							u_sequence:'02'
						},
					},
				};
			})
		);
	}
	    // 格式化日期
function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
        return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    let formattedDate;

    switch (outputFormat) {
        case "yyyy-mm-dd":
            formattedDate = `${year}-${month}-${day}`;
            break;
        case "yyyy-mm-dd HH:mm":
            formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
            break;
        case "yyyy-mm":
            formattedDate = `${year}-${month}`;
        break;
        // 可以根据需要继续添加其他格式的处理逻辑
        default:
            formattedDate = "不支持的输出格式";
    }

    return formattedDate;
}
})

//获取合同数量
function getCntCount(table,key,fun){
    if(!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return 
    $NG.execServer("getCntCount",{type:1,phid_pc:$NG.getCmpApi(table).getItem("phid_pc").getValue()},(res)=>{
      console.log(res,'count');
      switch(res.count){
        case 0:
          return
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects
          const temp_map = {}
          temp_map[key] = datas.phid
          temp_map[`${key}_EXName`] = datas.bill_name
          $NG.updateState((updater)=>{
            updater.data[table].setProps({
              ...temp_map
            })
            setTimeout(()=>{
              if(fun){
                fun()
              }
            },200)
          })
      }
    })
  }